unit UQueryThread;

interface

uses Classes, sysutils, controls, Forms, ADOdb, db;

type
  TDBQueryOpenThread = class (TThread)
  private
    FQuery          : TADOQuery;
    FDataSource     : TDataSource;
    FQueryException : Exception;
    procedure HookUpUI;
    procedure QueryError;
  protected
    procedure Execute; override;
  public
    constructor Create(Q: TADOQuery; D: TDataSource); virtual;
  end;

  TDBQueryExecThread = class (TThread)
  private
    FQuery          : TADOQuery;
    FEnabled        : TControl;
    FQueryException : Exception;
    procedure HookUpUI;
    procedure QueryError;
  protected
    procedure Execute; override;
  public
    constructor Create(Q: TADOQuery; E: TControl); virtual;
  end;


implementation

constructor TDBQueryOpenThread.Create(Q: TADOQuery; D: TDataSource);
begin
  inherited Create(True);
  FQuery := Q;
  FDataSource := D;
  FDataSource.DataSet := nil;
  FreeOnTerminate := True;
  Resume;
end;

procedure TDBQueryOpenThread.Execute;
begin
  try
    FQuery.Open;
    Synchronize(HookUpUI);
  except
    FQueryException := ExceptObject as Exception;
    Synchronize(QueryError);
  end;
end;

procedure TDBQueryOpenThread.HookUpUI;
begin
  FDataSource.DataSet := FQuery;
end;

procedure TDBQueryOpenThread.QueryError;
begin
  FDataSource.OnUpdateData(nil);
  Application.ShowException(FQueryException);
end;

// ========= EXEC ================
constructor TDBQueryExecThread.Create(Q: TADOQuery; E: TControl);
begin
  inherited Create(True);
  FQuery := Q;
  FEnabled := E;
  FreeOnTerminate := True;
  Resume;
end;

procedure TDBQueryExecThread.Execute;
begin
  try
    FQuery.Open;
    Synchronize(HookUpUI);
  except
    FQueryException := ExceptObject as Exception;
    Synchronize(QueryError);
  end;
end;

procedure TDBQueryExecThread.HookUpUI;
begin
  FEnabled.Enabled := True;
end;

procedure TDBQueryExecThread.QueryError;
begin
  Application.ShowException(FQueryException);
end;

end.
